#!/bin/bash

set -eu

export PATH="$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH"
source $SNAP/actions/common/utils.sh

if [ -e ${SNAP_DATA}/var/lock/clustered.lock ]
then
    echo "This MicroK8s deployment is acting as a node in a cluster."
    echo "Use 'snap start microk8s' to start services on this node."
    exit 0
fi

exit_if_no_permissions

PARSED=$(getopt --options=lho: --longoptions=help,output: --name "$@" -- "$@")
eval set -- "$PARSED"
while true; do
    case "$1" in
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo
            echo "Start Kubernetes services"
            echo
            echo "Options:"
            echo " -h, --help          Show this help"
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "$0: invalid option -- $1"
            exit 1
    esac
done


if ! run_with_sudo snap start ${SNAP_NAME} --enable
then
    echo 'Failed to start microk8s services. Check snapd logs with "journalctl -u snapd.service"'
    exit 1
else
    start_all_containers
    if run_with_sudo test -e ${SNAP_DATA}/var/lock/stopped.lock
    then
        # Mark the api server as starting
        run_with_sudo rm ${SNAP_DATA}/var/lock/stopped.lock &> /dev/null
    fi
fi

wait_for_node